﻿using System;
using System.Net.Mail;
using System.Text;
using System.Threading;
using Wedn.BLL.Data;

namespace Wedn.BLL.Common
{
    /// <summary>
    /// 电子邮件操作助手类
    /// </summary>
    public class EmailHelper
    {

        /// <summary>
        ///  发邮件方法
        /// </summary>
        /// <param name="recipients">收件人地址</param>
        /// <param name="subject">邮件主题</param>
        /// <param name="body">正文</param>
        /// <returns>是否发送成功</returns>
        public static bool Send(string recipients, string subject, string body)
        {
            try
            {
                MailAddress from = new MailAddress(OptionsManager.GetSetting("SiteEmailAddress"), OptionsManager.GetSetting("SiteEmailDisplayName"));
                MailMessage m = new MailMessage();
                m.From = from;

                m.To.Add(recipients);

                m.Subject = subject;
                m.Body = body;
                m.IsBodyHtml = true;
                m.Priority = MailPriority.Normal;
                m.BodyEncoding = Encoding.GetEncoding("utf-8");

                SmtpClient smtp = new SmtpClient();
                smtp.Host = OptionsManager.GetSetting("SmtpServer");
                smtp.Credentials = new System.Net.NetworkCredential(OptionsManager.GetSetting("SmtpUserName"), OptionsManager.GetSetting("SmtpPassword"));
                smtp.EnableSsl = Convert.ToBoolean(OptionsManager.GetSetting("SmtpEnableSsl"));
                smtp.Port = Convert.ToInt32(OptionsManager.GetSetting("SmtpServerPost"));
                smtp.Send(m);
                return true;
            }
            catch
            {
                //出现异常返回失败
                return false;
            }
        }

        /// <summary>
        /// 异步发邮件,如果超过一百封,仅发前一百封
        /// </summary>
        /// <param name="recipients"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        public static void SendAsync(string recipients, string subject, string body)
        {
            string[] emails = recipients.Split(',');
            int i = 0;
            foreach (string email in emails)
            {
                i++;
                if (i > 100)
                {
                    break;
                }
                string temp = email;
                ThreadPool.QueueUserWorkItem(delegate { Send(temp, subject, body); });
            }
        }
    }
}
